package com.lovely602.langchain4j.image.controller;


import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import dev.langchain4j.community.model.dashscope.WanxImageModel;
import dev.langchain4j.data.image.Image;
import dev.langchain4j.model.output.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 *  通义万象的模型调用
 * @author lizhixing
 */
@Slf4j
@RestController
@RequestMapping(value = "/image")
public class WanxImageModelController {


    @Autowired
    @Qualifier("wanxImageModel")
    private WanxImageModel wanxImageModel;

    @GetMapping(value = "/create1")
    public String create1(@RequestParam(value = "prompt", defaultValue = "生成一只可爱的小白猫", required = true) String prompt) throws IOException {

        Response<Image> imageResponse = wanxImageModel.generate(prompt);

        System.out.println(imageResponse.content().url());

        return imageResponse.content().url().toString();

    }

    @GetMapping(value = "/create2")
    public String create2() throws IOException {

        String prompt = "近景镜头，18岁的中国女孩，现代服饰，圆脸，微笑";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("AI_DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<watercolor>")
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;

        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e) {
            throw new RuntimeException(e.getMessage());
        }


        System.out.println(JsonUtils.toJson(result));

        return JsonUtils.toJson(result);

    }

}
